<?php
namespace app\index\controller;

use app\common\controller\IndexBase;
use app\api\controller\Upload;
use think\Db;

class Message extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }


    /**
     * 发送玩家消息
     * @return void
     */
    public function sendPlayerMsg()
    {
        $post = $this->request->post();
        $url = "";
        if($post['type'] == "image"){
            $result = $this->uploadImg($post['content']);
            if($result['error'] == 1){
                $this->error($result['message']);
            }
            $url = $result['url'];
        }
        $add_data = [
            'uid' => $post['uid'],
            'customer_id' => $post['customer_id'],
            'type' => 1,
            'content' => $post['type']=="text" ? $post['content'] : "",
            'images' => $url,
        ];
        $res = DB::connect('db_config_aiqi')->name('customer_detail')->insertGetId($add_data);
        //tab_customer_detail
        $this->success("发送成功！","",$res);
    }

    public function getPlayerMsg(){
        $post = $this->request->get();
        dump($post);exit;
        $this->success("发送成功！","",$data);
    }

    private function uploadImg($file)
    {
        $config = [
            'size' => 2097152, // 2MB限制
            'ext'  => 'jpg,gif,png,bmp,jpeg'
        ];

        $upload_path = str_replace('\\', '/', PATH . '/uploads');
        $save_path = '/uploads/';

        // 检查是否是Base64编码的图片数据
        if (is_string($file) && preg_match('/^data:image\/(\w+);base64,/', $file, $matches)) {
            try {
                $imageType = strtolower($matches[1]);

                // 验证图片类型
                if (!in_array($imageType, explode(',', $config['ext']))) {
                    throw new \Exception('不支持的图片格式');
                }

                // 提取Base64数据
                $base64Data = substr($file, strpos($file, ',') + 1);
                $imageData = base64_decode($base64Data);

                if ($imageData === false) {
                    throw new \Exception('Base64解码失败');
                }

                // 验证图片大小
                if (strlen($imageData) > $config['size']) {
                    throw new \Exception('图片大小超过限制');
                }

                // 创建与move()方法相同的目录结构 yyyymmdd/
                $sub_path = date('Ymd') . '/messsage/';
                if (!is_dir($upload_path . '/' . $sub_path)) {
                    mkdir($upload_path . '/' . $sub_path, 0755, true);
                }

                // 生成类似move()方法的文件名
                $savename = uniqid() . '.' . $imageType;
                $full_path = $upload_path . '/' . $sub_path . $savename;

                // 保存文件
                if (!file_put_contents($full_path, $imageData)) {
                    throw new \Exception('图片保存失败');
                }

                // 验证确实是图片文件
                if (!@getimagesize($full_path)) {
                    unlink($full_path); // 删除无效文件
                    throw new \Exception('上传的文件不是有效图片');
                }

                $result = [
                    'error' => 0,
                    'url' => $save_path . $sub_path . $savename
                ];

            } catch (\Exception $e) {
                $result = [
                    'error' => 1,
                    'message' => $e->getMessage()
                ];
            }
        }
        // 处理普通文件上传
        else {
            $info = $file->validate($config)->move($upload_path);

            if ($info) {
                $result = [
                    'error' => 0,
                    'url' => str_replace('\\', '/', $save_path . $info->getSaveName())
                ];
            } else {
                $result = [
                    'error' => 1,
                    'message' => $file->getError()
                ];
            }
        }

        return $result;
    }


}